package com.example.fairplay.newfpregistration.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fairplay.newfpregistration.R;
import com.example.fairplay.newfpregistration.util.StatusBarCompat;
import com.example.mylibrary.util.ToastUtils;

import java.util.Arrays;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.com.aratek.fp.Bione;
import cn.com.aratek.fp.FingerprintImage;
import cn.com.aratek.fp.FingerprintScanner;
import cn.com.aratek.util.Result;

/**
 * Created by fairplay on 2018/6/12.
 */

public class DistinguishFingerActivity extends BaseActivity {
	@Bind(R.id.iv_finger_result)
	ImageView ivFingerResult;
	@Bind(R.id.iv_finger_id)
	ImageView ivFingerId;
	@Bind(R.id.iv_finger_current)
	ImageView ivFingerCurrent;
	@Bind(R.id.tv_finger_result)
	TextView tvFingerResult;
	@Bind(R.id.text_title)
	TextView tvTitle;
	@Bind(R.id.button_backward)
	Button btnBack;
	private int NUMBER = 1;
	private FingerprintScanner mScanner;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_SHOW_INFO:
					Toast.makeText(DistinguishFingerActivity.this, (String) msg.obj,
							Toast.LENGTH_SHORT).show();
					break;
				case MSG_FP_RESULT:
					Result res = (Result) msg.obj;
					ivFingerCurrent.setImageBitmap(BitmapFactory.decodeByteArray(fi.convert2Bmp(), 0, fi.convert2Bmp().length, null));
					if (res.error == 0 && (Boolean) res.data) {
						ivFingerResult.setImageResource(R.drawable.pass);
						ToastUtils.Toast(context, "指纹验证成功");
						tvFingerResult.setText("指纹验证成功");
						tvFingerResult.setTextColor(Color.GREEN);
						mProgressDialog.dismiss();
						mHandler.postDelayed(new Runnable() {
							@Override
							public void run() {
								finish();
							}
						}, 3000);
					} else {
						ivFingerResult.setImageResource(R.drawable.nopass);
						tvFingerResult.setText("指纹验证失败");
						tvFingerResult.setTextColor(Color.RED);
						mProgressDialog.dismiss();
						if (NUMBER < 4) {
							ToastUtils.Toast(context, "第" + NUMBER + "次指纹比对失败,请再试一次");
							mHandler.postDelayed(new Runnable() {
								@Override
								public void run() {
									enroll();
									NUMBER++;
								}
							}, 1500);
						} else {
							ToastUtils.Toast(context, "指纹验证失败");
							mHandler.postDelayed(new Runnable() {
								@Override
								public void run() {
									finish();
								}
							}, 3000);
						}

					}
					break;
				case MSG_SHOW_PROGRESS_DIALOG:
					String[] info = (String[]) msg.obj;
					mProgressDialog.setTitle(info[0]);
					mProgressDialog.setMessage(info[1]);
					mProgressDialog.show();
					break;
				case MSG_DISMISS_PROGRESS_DIALOG:
					mProgressDialog.dismiss();
					break;
				default:
					break;
			}
		}
	};

	private Context context;
	private ProgressDialog mProgressDialog;
	private FingerprintImage fi;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_distinguish_finger);
		StatusBarCompat.compat(this, Color.rgb(7, 136, 242));
		context = this;
		Intent intent = getIntent();
		fpCardData = intent.getByteArrayExtra("fpinfo");
		ButterKnife.bind(this);
		initView();
		initObject();
		initData();
		setListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private static final String FP_DB_PATH = "/sdcard/fp.db";

	private void openDevice() {
		new Thread() {
			@Override
			public void run() {
				synchronized (DistinguishFingerActivity.this) {
					int error;
					if ((error = mScanner.powerOn()) != FingerprintScanner.RESULT_OK) {
						Log.i("---", "111111111111111111111");
						showInfoToast(getString(R.string.fp_power_on_failed));
						dismissProgressDialog();
						return;
					}
					if ((error = mScanner.open()) != FingerprintScanner.RESULT_OK) {
						Log.i("---", "2222222222222222222222");
						showInfoToast(getString(R.string.fp_open_failed));
						dismissProgressDialog();
						return;
					} else {
						Result res = mScanner.getSN();
						res = mScanner.getFirmwareVersion();
						Log.i("---", "3333333333333333333333333");
					}
					if ((error = Bione.initialize(DistinguishFingerActivity.this, FP_DB_PATH)) != Bione.RESULT_OK) {
						showInfoToast(getString(R.string.error_initialization_failed));
						Log.i("---", "44444444444444444444444444");
						return;
					}
					Log.i("---", "Fingerprint algorithm version: " + Bione.getVersion());
				}
			}
		}.start();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
//		startActivity(new Intent(this, ProjectPickActivity.class));
		finish();
	}

	private void closeDevice() {
		new Thread() {
			@Override
			public void run() {
				synchronized (DistinguishFingerActivity.this) {
					int error;
					if ((error = Bione.exit()) != Bione.RESULT_OK) {
						showInfoToast(getString(R.string.error_algorithm_cleanup_failed));
						dismissProgressDialog();
						return;
					}

					if ((error = mScanner.close()) != FingerprintScanner.RESULT_OK) {
						showInfoToast(getString(R.string.fp_close_failed));
						dismissProgressDialog();
						return;
					}
					if ((error = mScanner.powerOff()) != FingerprintScanner.RESULT_OK) {
						showInfoToast(getString(R.string.fp_power_off_failed));
						dismissProgressDialog();
						return;
					}
				}
			}
		}.start();
	}

	private byte[] fpCardData = null;
	private byte[] fpEnorllData = null;


	private static final int MSG_FP_RESULT = 0;
	private static final int MSG_SHOW_INFO = 1;
	private static final int MSG_CARD_INFO = 2;
	private static final int MSG_SHOW_PROGRESS_DIALOG = 3;
	private static final int MSG_DISMISS_PROGRESS_DIALOG = 4;
	private static final int MSG_RESULT_INFO = 6;
	private static final int MSG_INSERT_DATA = 7;
	private static final int MSG_FACE_RESULT = 8;
	private static final int MSG_VERIFY_INFO = 9;
	private static final int MSG_FP_INSERT_DATA = 10;


	private void enroll() {
		new Thread() {
			public void run() {
				showProgressDialog(getString(R.string.is_finding),
						getString(R.string.please_press_finger));
				Result res;
				mScanner.prepare();
				do {
					res = mScanner.capture();
				} while (res.error != FingerprintScanner.RESULT_OK);
				mScanner.finish();
				if (res.error == FingerprintScanner.RESULT_OK) {
					fi = (FingerprintImage) res.data;
					res = Bione.extractFeature(fi);
					if (res.error != Bione.RESULT_OK) {
						Log.e("res.error", "--->" + res.error);
						dismissProgressDialog();
						return;
					}
					fpEnorllData = (byte[]) res.data;

					Result vRes = Bione.idcardVerify(fpCardData, fpEnorllData);

					Log.e("fpCardData ", Arrays.toString(fpCardData));
					Log.e("fpEnorllData ", Arrays.toString(fpEnorllData) + "--->" + fpEnorllData.length);
					Log.e("error", String.valueOf(vRes.error));
					Log.e("data", String.valueOf(vRes.data));

					mHandler.sendMessage(mHandler.obtainMessage(MSG_FP_RESULT,
							vRes));
				} else {
					showInfoToast(getString(R.string.error_operation_failed));
				}
			}
		}.start();
	}


	@Override
	protected void initData() {

	}

	@Override
	protected void initView() {
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
		mProgressDialog.setIndeterminate(false);
		mProgressDialog.setCancelable(false);

		tvTitle.setText("指纹验证");
		if (fpCardData != null) {
			ivFingerId.setImageBitmap(BitmapFactory.decodeByteArray(fpCardData, 0, fpCardData.length, null));
		}
	}

	@Override
	protected void initObject() {
		if (mScanner == null) {
			mScanner = FingerprintScanner.getInstance(this);
		}
		openDevice();
		enroll();
	}

	@Override
	protected void setListener() {
		btnBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	private void showProgressDialog(String title, String message) {
		mHandler.sendMessage(mHandler.obtainMessage(MSG_SHOW_PROGRESS_DIALOG,
				new String[]{title, message}));
	}

	private void dismissProgressDialog() {
		mHandler.sendMessage(mHandler
				.obtainMessage(MSG_DISMISS_PROGRESS_DIALOG));
	}

	private void showInfoToast(String info) {
		mHandler.sendMessage(mHandler.obtainMessage(MSG_SHOW_INFO, info));
	}

	@Override
	protected void onDestroy() {
		closeDevice();
		super.onDestroy();
	}
}
